package cn.epsilon3.handler;

import cn.epsilon3.common.Result;
import cn.epsilon3.constant.ResultEnum;
import cn.epsilon3.media.ses.tencent.service.TencentSesWarnClient;
import cn.hutool.core.lang.UUID;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@ControllerAdvice
public class ExceptionSesHandler {

    private static final Log log = LogFactory.get();

    @Resource
    private TencentSesWarnClient tencentSesWarnClient;

    /**
     * 捕捉异常返回
     *
     * @param e 异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionResult(Exception e) {
        String uuid = UUID.randomUUID().toString();
        log.error(e + ":" + uuid);
        e.printStackTrace();
        tencentSesWarnClient.exceptionWarnEmail("千渝开放平台",uuid,getExceptionAllInformation(e));
        return new Result<>(ResultEnum.ERROR,"哎呀，发生了点小意外" + uuid);
    }

    /**
     * 获取异常相信信息
     *
     * @param exception 异常
     * @return
     */
    private static String getExceptionAllInformation(Exception exception) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        exception.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
        }
        return ret;
    }
}
